/**
 * Leaflet Map Service
 * leaflet地图控制服务，添加图层、添加几何体和视图，操作地图
 */

angular.module('JiangGanApp')
  .service('LeafletService', ['$http','ColorService', 'GpsService', 'DataService', LeafletService]);


function LeafletService($http, ColorService, GpsService, DataService) {

	//设置参考坐标系，用于转换百度地图便宜
	var crs = new L.Proj.CRS('EPSG:900913',
	  '+proj=merc +a=6378206 +b=6356584.314245179 +lat_ts=0.0 +lon_0=0.0 +x_0=0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs',
	  {
	    resolutions: function () {
	      level = 19
	      var res = [];
	      res[0] = Math.pow(2, 18);
	      for (var i = 1; i < level; i++) {
	        res[i] = Math.pow(2, (18 - i))
	      }
	      return res;
	    }(),
	    origin: [0,0],
	    bounds: L.bounds([20037508.342789244, 0], [0, 20037508.342789244])
	  }
	),
	map = L.map('map', {
	  crs: crs
	});
	
	var center = [30.32, 120.23];
	//本地地图切片
	var tileUrl = 'http://10.118.43.78:7777/1082287436/{z}/{x}/{y}';
	var tileUrlDark = 'http://10.118.43.78:7778/1082287436/{z}/{x}/{y}';
	new L.TileLayer(tileUrl, {
	  maxZoom: 18,
	  minZoom: 6,
	  attribution: 'MAP',
	  tms: true
	}).addTo(map);
	map.setView(center, 13);

	//设置显示区域
	// map.setMaxBounds([[30.1178, 119.9877], [30.7872, 121.2082]]);

	//已加载的图层
	var onlayers = [];
	/*
		清楚地图上的图层
	*/
	this.clearLayers = function () {
		for(var i = 0; i < onlayers.length; i++){
			map.removeLayer(onlayers[i]);
		}
		onlayers = [];
		map.setView(center, 13, {duration: 1});
	}
	/*
		在地图上添加标记点
		latlng：经纬度坐标, [lat, lon]
		img: 标记图片位置
		imgSize: 图片显示长高,
		msg: 标记显示信息
	*/
	this.addMarker = function (lat, lng, img, imgSize, msg) {
		var icon = L.icon({
		  iconUrl: img,
		  iconSize: imgSize,
		  iconAnchor: [imgSize[0] / 2, imgSize[1]],
		  popupAnchor: [0, imgSize[1]]
		});
		var marker = L.marker(GpsService.bd_encrypt(lat, lng), {icon: icon}).bindPopup(msg).addTo(map);
		onlayers.push(marker);
	}

	/*
		在地图上添加标记集群，缩放聚合
		data: 数据点集合，包括位置和显示信息
		img: 标记图片位置
		imgSize: 图片显示长高,
	*/
	this.addMarkers = function (data, attrs, img, imgSize) {
		var markers = L.markerClusterGroup();
		var icon = L.icon({
		  iconUrl: img,
		  iconSize: imgSize,
		  iconAnchor: [imgSize[0] / 2, imgSize[1]],
		  popupAnchor: [0, - imgSize[1]]
		});
		for(var i = 0; i < data.length; i++) {
			if(data[i][attrs.lat] == 'NULL') {
				continue;
			}
			markers.addLayer(L.marker(GpsService.bd_encrypt(data[i][attrs.lat] - 0, data[i][attrs.lng] - 0), 
				{icon: icon}).bindPopup(data[i][attrs.msg]));
		}
		map.addLayer(markers);
		onlayers.push(markers);
	}

	/*
		data: 方格数组，包括位置坐标，统计数量value
		param：其他参数，包括最小经纬度[minlng, minlat]，经纬度间隔s，最大统计数maxValue
	*/
	this.drawSquare = function (data, param) {
		for(var i = 0; i < data.length; i++){
			var item = data[i];
			var lng = param.minlng + item.lngNo * param.s;
			var lat = param.minlat + item.latNo * param.s;
			var latlng = GpsService.bd_encrypt(lat, lng);
			var value = item.value;
			var color = ColorService.getColorDark(value, param.maxValue);
			var bounds = [[latlng[0], latlng[1]], [latlng[0] + param.s, latlng[1] + param.s]];
			var rect = L.rectangle(bounds, {color: color, weight: 0, fillOpacity: 0.4}).addTo(map);
			onlayers.push(rect);
		}
	}

	/*
		points: 派出所边界数据
		drawStations：描绘派出所形状
	*/
	var points = [];
	DataService.restGetApi('communities').then(function success(data) {
		points = data;
	});
  // $.getJSON('../data/paichusuo.json', function (resp){
  //    points = resp.geometries;
  // });
	this.drawStations = function (data, maxValue) {
		for(var i = 0; i < points.length; i++) {
			var latlngs = [];
			var area = points[i].area.split(';');
			for(var j = 0; j < area.length; j++){
				var latlng = area[j].split(',');
        latlngs.push(latlng);
      }
      var color = ColorService.getColorArea(data[points[i].community], maxValue);
      // color = '#00FF99';
      var polygon = L.polygon(latlngs, {color: '#587DC1', weight: 1, fillColor: color, fillOpacity: 0.7})
      	.bindPopup(points[i].street + ' ' + points[i].community).addTo(map);
      onlayers.push(polygon);
		}
	}

	/*
		热力图，
		data: [[lat, lng, count], ...]
	*/
	this.drawHeatmap = function (data) {
		var heat = L.heatLayer(data, {
			radius: 25,
			// minOpacity: 0.1,
			gradient: {
				1: 'red', 
				0.8: 'orange', 
				0.6: 'yellow', 
				0.5: '#A1E125', 
				0.4: '#00FE61'
			}, 
		}).addTo(map);
		onlayers.push(heat);
	}

	/*
		轨迹图
		data: {latlngs: [[lat, lng], ...]}
	*/
	this.drawTrack = function (data) {
		var icon = L.icon({
		  iconUrl: 'img/point.png',
		  iconSize: [18, 19],
		  iconAnchor: [9, 9.5],
		  popupAnchor: [0, 9.5]
		});
		onlayers.push(L.polyline(data.latlngs, {color: '#99E200'}).addTo(map));
		for(var i = 0; i < data.latlngs.length; i++) {
			onlayers.push(L.marker(data.latlngs[i], {icon: icon}).addTo(map));
		}
	}

}